import router from './router'
import store from './store'

// 全局路由守卫
router.beforeEach(async(to, from, next) => {
  const token = store.state.user.token
  const nextTo = ['/', '/login'] // 白名单
  if (token) {
    // 如果访问的是登录页，跳转到主页
    if (to.path === '/login') {
      next('/')
    } else {
      await store.dispatch('user/getUserInfo')
      // 必须先把页面加载完，再发送请求
      next()
    }
  } else {
    // 是否在白名单内
    if (nextTo.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
